package main

import (
	"fmt"
	"net/http"
	"strconv"
	"sync/atomic"
	"time"
)

var reqNums atomic.Uint64

func main() {
	var err error
	fmt.Println("Start Web")
	err = StartWeb(":8081")
	if err != nil {
		fmt.Println("WebStartError:", err.Error())
	}
}

// ioBoundTask 模拟I/O密集型任务
func ioBoundTask() {
	time.Sleep(100 * time.Millisecond)
}

//// cpuIntensiveTask 模拟CPU密集型任务 (计算斐波那契数)
//func cpuIntensiveTask(compN int64) int64 {
//	var a int64
//	var b int64 = 1
//	var c int64 = 1
//	var tmpI int64
//	if compN <= 1 {
//		return compN
//	}
//	// 调整循环次数 (compN) 以消耗足够的 CPU 时间
//	compN = compN*100000 + 1
//	for tmpI = 2; tmpI < compN; tmpI++ {
//		c = a + b
//		a = b
//		b = c
//	}
//	return b
//}

// StartWeb 启动WEB服务
func StartWeb(svrAddr string) error {
	var err error
	http.HandleFunc("/test", ThreadTest01)
	err = http.ListenAndServe(svrAddr, nil)
	if err != nil {
		fmt.Println("WebStartError:", err.Error())
	}
	return err
}

func ThreadTest01(w http.ResponseWriter, r *http.Request) {
	var reData []byte
	var result int64
	var tmpResult string
	var tmpRandN uint64
	var tmpRandNStr string
	// 1. 模拟I/O等待
	ioBoundTask()

	// 2. 模拟CPU计算
	tmpRandN = reqNums.Load()
	result = CpuIntensiveTaskUnrolled4(int64(tmpRandN % 50))
	tmpResult = strconv.FormatInt(result, 10)
	tmpRandNStr = strconv.Itoa(int(tmpRandN))
	//fmt.Println("Count:", tmpRandN, " RandN:", tmpRandNStr, "Result:", tmpResult)
	reData = []byte(`{"message":"Processed successfully by Go","count:"` + tmpRandNStr + `,"hash":` + tmpResult + `}`)
	_, _ = w.Write(reData)
	reqNums.Add(1)
	return
}

// CpuIntensiveTaskUnrolled4 4次循环展开（可能更适合CPU缓存）
func CpuIntensiveTaskUnrolled4(compN int64) int64 {
	if compN <= 1 {
		return compN
	}
	compN = compN*100000 + 1

	var a, b int64 = 0, 1
	i := int64(2)

	for ; i+4 <= compN; i += 4 {
		a, b = b, a+b
		a, b = b, a+b
		a, b = b, a+b
		a, b = b, a+b
	}

	for ; i < compN; i++ {
		a, b = b, a+b
	}

	return b
}
